package 力扣_树算法.遍历;

import java.util.*;

/**589. N 叉树的前序遍历
 * @author zx
 * @create 2022-04-18 18:24
 */
public class N叉树的前序遍历_589 {
    /**
     * @return 递归(这个必须掌握)
     */
    public List<Integer> preorder2(Node root) {
        List<Integer> res = new ArrayList<>();
        helper(root,res);
        return res;
    }
    private void helper(Node root,List<Integer> list){
        if(root == null){
            return;
        }
        list.add(root.val);
        for(Node node : root.children){
            helper(node,list);
        }
    }

    /**
     * @return 迭代做法,代码简单,思维量巨大(官方题解(最好的))
     */
    public List<Integer> preorder(Node root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Deque<Node> stack = new ArrayDeque<Node>();
        stack.push(root);
        while (!stack.isEmpty()) {
            Node node = stack.pop();
            res.add(node.val);
            for (int i = node.children.size() - 1; i >= 0; --i) {
                stack.push(node.children.get(i));
            }
        }
        return res;
    }
}
class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, List<Node> _children) {
        val = _val;
        children = _children;
    }
}
